package cn.itsource.system.service.impl;

import cn.itsource.system.domain.Role;
import cn.itsource.system.domain.Role;
import cn.itsource.system.mapper.RoleMapper;
import cn.itsource.system.query.RoleQuery;
import cn.itsource.system.query.RoleQuery;
import cn.itsource.system.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional

    public void save(Role role) {
        if(role.getId() == null){
            //保存角色
            roleMapper.insert(role);
            //维护角色和菜单关系
            roleMapper.saveRoleMenus(role);
            //维护角色和权限之间的关系
            roleMapper.saveRolePermissions(role);
        }else {
            //role的更改 需要先把原来的菜单和权限删除 然后在进行更新
            roleMapper.deleteRoleMenuByRoleId(role.getId());
            roleMapper.deleteRolePermissionByRoleId(role.getId());
            roleMapper.updateByPrimaryKeySelective(role);
            //维护角色和菜单关系 删完过后 更新需要从新把菜单和权限加入
            if (role.getMenuIds().size()>0){
                roleMapper.saveRoleMenus(role);
            }
            if (role.getPermissionIds().size()>0){
                //维护角色和权限之间的关系
                roleMapper.saveRolePermissions(role);
            }

        }
    }

    @Override
    @Transactional

    public int deleteByPrimaryKey(Long id) {
        return roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Role selectByPrimaryKey(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<Role> pageInfo(RoleQuery roleQuery) {
        PageHelper.startPage(roleQuery.getCurrentPage(),roleQuery.getPageSize());
        List<Role> roles = roleMapper.selectAllByQuery(roleQuery);
        return new PageInfo<Role>(roles);
    }

    @Override
    @Transactional
    public void deleteByCollection(List<Role> roles) {
        roleMapper.deleteByConllection(roles);
    }

}
